package com.xudow.app.newui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.umeng.message.PushAgent;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.module.guide.ClazzActivity;
import com.xudow.app.newui.base.BaseUiActivity;
import com.xudow.app.newui.home.HomeActivity;
import com.xudow.app.ui.MobilePhoneBindActivity;
import com.xudow.app.ui.task.LoginTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.ui.task.user.RelatedAccountAddTask;
import com.xudow.app.ui.widget.TitleBarTextView;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;

public class AgencyLoginActivity extends BaseUiActivity implements View.OnClickListener {
    @BindView(R.id.login_btn)
    TextView login_btn;

    @BindView(R.id.account_et)
    EditText account_et;

    @BindView(R.id.pwsd_et)
    EditText pwsd_et;

    @BindView(R.id.title)
    TitleBarTextView title;

    String agencyId;
    private boolean gotohome = true;//登录后进入主页面
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agency_login);
        title.setText(getIntent().getStringExtra("title"));
        agencyId=getIntent().getStringExtra("agencyId");


    }

    @Override
    protected void initData() {

    }

    public void onBackBtnClick(View view){
        finish();
    }
    @Override
    protected void initListener() {
        login_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String username = account_et.getText().toString().trim();
        if (StringUtils.isEmpty(username)) {
            account_et.setError(getResources().getString(R.string.username_required));
            return;
        }

        String password = pwsd_et.getText().toString().trim();
        if (StringUtils.isEmpty(password)) {
            pwsd_et.setError("密码不能为空");
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("username", username);
        params.put("password", password);
        params.put("agencyId", agencyId);
        showLodingDialog(getString(R.string.login_prompt));

        LoginTask loginTask = new LoginTask(this, loginHandler);
        addTask(loginTask);
        loginTask.execute(params);

        showLodingDialog(getString(R.string.processing));




    }

    /**
     * 登陆处理Handler
     */
    private Handler loginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (LoginTask.LOGIN_SUCCESS == msg.what) {
                getMyApp().freshlogin=true;

                UserProfileTask userProfileTask = new UserProfileTask(AgencyLoginActivity.this, userprofileHandler);
                addTask(userProfileTask);
                userProfileTask.execute();
            } else if (LoginTask.LOGIN_FAIL == msg.what) {
                Bundle bundle = msg.getData();
                String errMsg = bundle.getString("errorMessage");

                Toast.makeText(AgencyLoginActivity.this, errMsg, Toast.LENGTH_LONG).show();
            } else {
                String toastMsg = getString(R.string.common_fail_connect_server);
                Toast.makeText(AgencyLoginActivity.this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                UserProfileWithOther profile = ud.getUserDetail();

                try {
                    PushAgent.getInstance(AgencyLoginActivity.this).enable();
                    PushAgent.getInstance(AgencyLoginActivity.this).addAlias(profile.getName(), Config.XUDOW_UMENG_MSG_ALIAS);
                    PushAgent.getInstance(AgencyLoginActivity.this).addExclusiveAlias(profile.getName(), Config.XUDOW_UMENG_MSG_ALIAS);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                XApplication application = (XApplication) getApplication();
                application.setUserProfileId(profile.getId());
                application.setProfile(profile);

                //用户必须绑定手机号
                if (StringUtils.isEmpty(profile.getMobilePhone())) {
                    startActivity(new Intent(AgencyLoginActivity.this, MobilePhoneBindActivity.class));
                } else if (!XApplication.getInstance().isHasAttentionType()) {
                    Intent intent = new Intent(AgencyLoginActivity.this, ClazzActivity.class);
                    intent.putExtra("isLogin", true);
                    startActivity(intent);
                }else if (gotohome) {
                    startActivity(new Intent(AgencyLoginActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                }


                finish();
            } else {
                //TODO:获取用户信息失败处理
            }
        }
    };
}
